<template>
  <div class="page opening">
    <div
      id="loading-panel"
      v-show="!hideloading"
    >
      <h1><strong>Loading...{{percent}}</strong></h1>
    </div>
    <van-button
      round
      type="danger"
      class="skip"
      v-show="activeIndex == total-1"
      @click="backHome"
    >返回首页</van-button>
    <a
      class="inner"
      href="javascript:void(0);"
      v-show="activeIndex == index"
      v-for="(item,index) in list"
      :key="index"
      :style="{backgroundImage: 'url('+item+')' }"
    ></a>
  </div>
</template>

<script>
export default {
  name: 'opening',
  data () {
    return {
      count: 0,//加载图片数
      percent: '',//百分比
      hideloading: false,
      timer: '',//定时器
      activeIndex: 0,//当前帧数
      total: 75,//所有帧数
      list: []//图片列表
    }
  },
  methods: {
    addList () {
      for (let index = 0; index < this.total; index++) {
        if (index < 10) {
          this.list.push('http://smart.syruptech.cn/test0613/static/video/front0' + index + '.jpg');
        } else {
          this.list.push('http://smart.syruptech.cn/test0613/static/video/front' + index + '.jpg');
        }
      }
    },
    videoPlay () {
      this.activeIndex++;
      if (this.activeIndex >= 74) {
        window.clearInterval(this.timer);
      }
    },
    preload: function () {
      let imgs = this.list;

      for (let img of imgs) {
        let image = new Image();
        image.src = img
        image.onload = () => {
          this.count++
          // 计算图片加载的百分数，绑定到percent变量
          let percentNum = Math.floor(this.count / this.total * 100);
          this.percent = `${percentNum}%`;
        }
      }
    },
    backHome () {
      this.$router.replace({ name: 'home' });
    }
  },
  mounted () {
    this.addList();
    this.preload();
  },
  watch: {
    count: function (val) {
      if (val === this.total) {
        setTimeout(() => {
          this.hideloading = true;
          this.timer = setInterval(this.videoPlay, 70);
        }, 1000);
      }
    }
  },
  beforeDestroy () {
    clearInterval(this.timer);
  }
}
</script>

<style lang="less" scoped>
.opening {
  padding: 0;
}
#loading-panel {
  z-index: 19911002;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  font-size: 0.24rem;
  h1,
  h2 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
.inner {
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
}
.skip {
  position: absolute;
  z-index: 1991;
  bottom: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

